package com.module.content.ui.info.adapter

import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import com.allen.app.data.bean.Attachments
import com.allen.base.base.basic.extras.load
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.module.content.R
import com.module.content.helper.ImageCalculateHelper
import com.module.content.helper.InfoVideoPlayHelper

/**
 * author : Allen
 * date   : 2020/08/21
 * time   : 10:13
 * desc   :
 */
class InfoImageItemAdapter(private val count: Int) :
    BaseQuickAdapter<Attachments, BaseViewHolder>(R.layout.info_image_item) {

    private var infoVideoPlayHelper: InfoVideoPlayHelper? = null

    override fun convert(holder: BaseViewHolder, item: Attachments) {
        if (infoVideoPlayHelper == null) infoVideoPlayHelper = InfoVideoPlayHelper(context, true)
        val contentLayout = holder.getView<FrameLayout>(R.id.contentLayout)
        val imageSize = ImageCalculateHelper.getImageSize(item.image_size?.m, count, count == 1)
        //按比例缩放，动态修改图片大小
        val params = contentLayout.layoutParams
        if (imageSize != null) {
            if (count == 1) {
                params.width = imageSize.width
                params.height = imageSize.height
            } else {
                params.width = FrameLayout.LayoutParams.MATCH_PARENT
                params.height = imageSize.width
            }
        }
        //单张图片显示
        val ivCover = holder.getView<ImageView>(R.id.ivCover)
        if (item.format == "gif") {
            holder.setGone(R.id.gifHintTv, false)
            ivCover.load(item.pic_url, 4f)
        } else {
            holder.setGone(R.id.gifHintTv, true)
            ivCover.load(item.high_url, 4f)
        }
        ivCover.setOnClickListener {
            setVideoPlayer(
                contentLayout,
                item.low_url,
                holder.adapterPosition,
                true
            )
        }
    }

    fun setVideoPlayer(
        contentLayout: FrameLayout?,
        mediaPath: String?,
        position: Int,
        play: Boolean = false
    ) {
        infoVideoPlayHelper?.setVideoPlayer(contentLayout, mediaPath, position, play)
    }

    fun stop() {
        infoVideoPlayHelper?.stop()
    }

    fun onChildViewDetachedFromWindow(view: View) {
        infoVideoPlayHelper?.onChildViewDetachedFromWindow(view)
    }
}